package servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Customer;
import service.CustomerManager;
import service.impl.CustomerManagerFactory;
import utils.Format;

/**
 * Servlet implementation class UpDateCustomerServlet
 */
public class UpDateCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerManager manager;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpDateCustomerServlet() {
        super();
        manager = CustomerManagerFactory.getInstance();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String sal = request.getParameter("sal");
		String sex = request.getParameter("sex");
		String birth = request.getParameter("birth");
		String[] favs = request.getParameterValues("favs");
		String favsStr =""; 
		boolean first = true;
		for(String str:favs){
			if(first){
				favsStr+=str;
				first = false;
			}else{
				favsStr+=","+str;
			}
			
		}
		//校验
		boolean verifyDate = Format.verifyDate(birth);
		if(!verifyDate){
			response.sendRedirect("error");
			return;
		}
		//类型转换
		Integer cid = Integer.parseInt(id);
		double csal = Double.parseDouble(sal);
		boolean csex = Boolean.parseBoolean(sex);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date cbirth = null;
		try {
			cbirth = sdf.parse(birth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//封装
		Customer c = new Customer(cid, name, csal, csex, cbirth,favsStr);
		int m = manager.updateCustomer(c);
		if(m>0){
			response.sendRedirect("loadAll");
		}else{
			response.sendRedirect("error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
